let util = require('util');
let mysqlPool = require('../dao/MySQLPool');

class LogCoinChangeDao {
    constructor() {
    }

    /**
     *
     * @param {{uid: String, name: String, phone: String, page: Number}} cond
     * @returns {Promise<Array>}
     */
    async queryByCond(cond) {
        let sql = 'select l.uid, u.name, IFNULL(u.phone, \'\') phone,  l.oldCoin, l.newCoin, l.cvalue alterNum, l.updateEvent event, IFNULL(s.amt, 0)  bankCoins, l.time alterTime from log_coinnum_change l ' +
            ' left join users u on u.uid = l.uid ' +
            ' left join safebox s on s.uid = l.uid ' +
            ' where 1=1';
        let args = [];
        if (cond.uid){
            args.push(cond.uid);
            sql += ' and l.uid = ?';
        }

        if (cond.name){
            args.push(cond.name);
            sql += ' and u.name = ?';
        }

        if (cond.phone){
            args.push(cond.phone);
            sql += ' and u.phone = ?';
        }


        if (!cond.page){
            cond.page = 1;
        }

        let idStart = (cond.page-1) * 10;
        args.push(idStart);
        sql += ' order by l.id desc';
        sql += " limit ?, 10";

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }

        return [];
    }

    /**
     *
     * @param {{uid: String, name: String, phone: String, page: Number}} cond
     * @returns {Promise<Number>}
     */
    async queryByCondCnt(cond) {
        let sql = 'select count(1) cnt from log_coinnum_change l ' +
            ' left join users u on u.uid = l.uid ' +
            ' left join safebox s on s.uid = l.uid ' +
            ' where 1=1';
        let args = [];
        if (cond.uid){
            args.push(cond.uid);
            sql += ' and l.uid = ?';
        }

        if (cond.name){
            args.push(cond.name);
            sql += ' and u.name = ?';
        }

        if (cond.phone){
            args.push(cond.phone);
            sql += ' and u.phone = ?';
        }

        let res = await mysqlPool.query(sql, args);
        if (res){
            return res[0].cnt;
        }

        return 0;
    }
}

let logCoinChangeDao = new LogCoinChangeDao();
module.exports = logCoinChangeDao;